package com.higold.cloud.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.higold.cloud.R
import com.higold.cloud.base.BaseActivity
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.scwang.smartrefresh.layout.util.DensityUtil
import android.view.ViewTreeObserver
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.higold.cloud.mvp.model.bean.Common
import com.higold.cloud.showToast
import com.higold.cloud.ui.adapter.ManagerListAdapter
import com.higold.cloud.view.RecyclerViewDivider
import com.gyf.immersionbar.ktx.immersionBar
import com.higold.cloud.mvp.contract.RegionalDetailContract
import com.higold.cloud.mvp.model.bean.regionalDetail.RegionalDetail
import com.higold.cloud.mvp.presenter.RegionalDetailPresenter
import com.higold.cloud.net.exception.ErrorStatus
import com.higold.cloud.utils.AppUtils
import com.higold.cloud.utils.CleanLeakUtils
import kotlinx.android.synthetic.main.activity_manager_detail.*


/**
 *    author : lxz
 *    date   : 2019/8/16 17:35
 *    desc   :
 */

class ManagerDetailActivity : BaseActivity(), RegionalDetailContract.View {

    companion object {
        private val TOTAL_COUNTER = 24
        private val PAGE_SIZE = 8
    }

    private var data: com.higold.cloud.mvp.model.bean.regionalList.Data? = null

    private val mPresenter by lazy { RegionalDetailPresenter() }

    private lateinit var mAdapter: ManagerListAdapter

    private var mCurrentCounter = 0

    private var isErr: Boolean = false

    private var mOffset = 0
    private var mScrollY = 0
    private var mWidth = 0f

    init {
        mPresenter.attachView(this)
    }

    override fun layoutId(): Int = R.layout.activity_manager_detail

    override fun setRegionalList(regionalDetail: RegionalDetail) {
        multipleStatusView.showContent()
        setAdapter(regionalDetail)
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            multipleStatusView.showNoNetwork()
        } else {
            multipleStatusView.showError()
        }
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {

    }

    override fun start() {
        mPresenter.requestRegionalDetail(data!!.saleman_id)
    }

    override fun onDestroy() {
        CleanLeakUtils.fixInputMethodManagerLeak(this)
        super.onDestroy()
    }

    override fun initData() {
        data = intent.getSerializableExtra("Regional_Info") as com.higold.cloud.mvp.model.bean.regionalList.Data
        setTopData(data!!)
    }

    override fun initView() {
        //状态栏透明和间距处理
//        StatusBarUtil.setPaddingSmart(this, toolbar)
        scrollView.scrollTo(0, 0)

        ll_pb.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                mWidth = ll_pb.measuredWidth.toFloat()
                ll_pb.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onHeaderPulling(header: RefreshHeader?, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                parallax.translationY = (mOffset - mScrollY).toFloat()
                toolbar.alpha = 1 - Math.min(percent, 1f)
            }

            override fun onHeaderReleasing(header: RefreshHeader?, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                parallax.translationY = (mOffset - mScrollY).toFloat()
                toolbar.alpha = 1 - Math.min(percent, 1f)
            }

        })

        scrollView.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            private var lastScrollY = 0
            private val h = DensityUtil.dp2px(170f)
            private val color = ContextCompat.getColor(applicationContext, R.color.colorPrimary) and 0x00ffffff
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onScrollChange(v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                var tScrollY = scrollY
                if (lastScrollY < h) {
                    tScrollY = Math.min(h, tScrollY)
                    mScrollY = if (tScrollY > h) h else tScrollY
//                    StatusBarUtil.immersive(this@ManagerDetailActivity, R.color.colorAccent, 1f * mScrollY / h)

                    immersionBar {
                        statusBarColor(R.color.colorAccent)
                        navigationBarColor(R.color.colorPrimary)
                        barColorTransform(R.color.colorPrimary)
                        titleBar(toolbar)
                        barAlpha(1f * mScrollY / h)
                    }

                    buttonBarLayout.alpha = 1f * mScrollY / h
                    toolbar.setBackgroundColor(255 * mScrollY / h shl 24 or color)
                    toolbar.navigationIcon!!.setTint(255 * mScrollY / h shl 24 or resources.getColor(R.color.colorAccent))
                    parallax.translationY = (mOffset - mScrollY).toFloat()
                }
                lastScrollY = tScrollY
                if (lastScrollY == 0) {
                    tv_header_title.visibility = View.VISIBLE
                    buttonBarLayout.visibility = View.GONE
                    toolbar.navigationIcon!!.setTint(Color.WHITE)
                    immersionBar { statusBarDarkFont(false).navigationBarDarkIcon(false) }
                } else {
                    tv_header_title.visibility = View.GONE
                    buttonBarLayout.visibility = View.VISIBLE
                    immersionBar { statusBarDarkFont(true).navigationBarDarkIcon(true) }
                }
            }
        })

        buttonBarLayout.alpha = 0f
        toolbar.setBackgroundColor(0)
        //返回
        toolbar.setNavigationOnClickListener { finish() }

        refreshLayout.setOnRefreshListener {
            Handler().postDelayed({
                mPresenter.requestRegionalDetail(data!!.saleman_id)
            }, 1500)
        }

    }

    private fun setAdapter(regionalDetail: RegionalDetail) {

        if (refreshLayout.isRefreshing) {
            refreshLayout.finishRefresh()
            scrollView.scrollTo(0, 0)

            mAdapter.replaceData(regionalDetail.data)
            rv_manager_detail.scheduleLayoutAnimation()
            isErr = false
            mCurrentCounter = PAGE_SIZE
            mAdapter.setEnableLoadMore(true)
        } else {
            mAdapter = ManagerListAdapter(regionalDetail.data)
            mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT)

            rv_manager_detail.addItemDecoration(RecyclerViewDivider(this, LinearLayoutManager.VERTICAL, 10,
                    ContextCompat.getColor(this, R.color.divide_gray_color)))

            rv_manager_detail.adapter = mAdapter
            rv_manager_detail.layoutManager = LinearLayoutManager(this)

            rv_manager_detail.addOnItemTouchListener(object : OnItemClickListener() {
                override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

                }
            })
        }
    }

    @SuppressLint("SetTextI18n")
    private fun setTopData(data: com.higold.cloud.mvp.model.bean.regionalList.Data) {
        tv_manager_name.text = data.saleman
        tv_job.text = data.shortName + "-大区经理"
        tv_goal.text = AppUtils.changeFloatToString(data.saleAmount) + "w / " + AppUtils.changeFloatToString(data.missionAmount) + "w本月"
        tv_percent.text = AppUtils.changeFloatToString((data.saleAmount / data.missionAmount) * 100) + "%"
        tv_title.text = data.saleman

        val rate = (data.saleAmount / data.missionAmount).toFloat()
        when (rate) {
            in 0..50 -> pb_plan.setLevel(0)
            in 51..100 -> pb_plan.setLevel(1)
            else -> pb_plan.setLevel(2)
        }

        pb_plan.progress = ((data.saleAmount / data.missionAmount) * 100).toFloat()
        pb_plan.duration = 1500
        pb_plan.startAnim()
    }

    private fun getData(lenth: Int): ArrayList<Common> {
        val list = ArrayList<Common>()
        for (i in 0 until lenth) {
            val common = Common()
            common.size = (i)
            list.add(common)
        }
        return list
    }

}